import {
  API_DOMAIN
} from '../../utils/api.config'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ifTeacher: true, //ture 为老师  false为家长身份
    // showModal: false, // 显示modal弹窗
    // single: true // false 只显示一个按钮，如果想显示两个改为true即可
    headImg: '',
    userInfo: {},
    name: '',
    className: '',
    showImg: true,//倒三角默认不显示

    stuIndex: 0,
    selected: {},
    ifShowTeacherBut: false,
    ifShowStuInfo: false,
    picUrl: ''
  },

  //切换角色
  tabJuese: function () {
    this.hidePop()
    this.updateUserType()
  },

  // // 点击取消按钮的回调函数
  // modalCancel:function(e) {
  //   // 这里面处理点击取消按钮业务逻辑
  //   console.log('点击了取消')
  // },
  // // 点击确定按钮的回调函数
  // modalConfirm:function(e) {
  //   // 这里面处理点击确定按钮业务逻辑
  //   console.log('点击了确定')
  // },
  browse: function () {
    this.hidePop()
    let that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album');
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera');
          }
        }
      }
    })
  },

  /*打开相册、相机 */
  chooseWxImage: function (type) {
    let that = this;
    wx.chooseImage({
      count: 1,// 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: [type],// 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        //  返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          aimgurl: res.tempFilePaths
        });
        console.log("=文件路径==" + that.data.aimgurl);

        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: API_DOMAIN + '/api/file/image', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          // formData:{
          //   'user': 'test'
          // },
          header: {
            'content-type': 'application/json', // 默认值
            'X-AUTH-SESSION': wx.getStorageSync('tokenId')
          },
          success: function (res) {
            var str = JSON.parse(res.data)
            if ("BASE.000" == str.code) {
              that.setData({
                picUrl: str.data.url,
              })
            }
            that.updateUserPicUrl()
          }
        })
      }
    })
  },


  updateUserPicUrl() {
    wx.showLoading({
      title: '头像更新中...',
      icon: 'none',
    })

    var vType
    var vId

    if (this.data.ifTeacher) {
      vType = 1
      vId = this.data.userInfo.appUserId
    } else {
      vType = 2
      vId = this.data.userInfo.list[this.data.stuIndex].studentId
    }

    var data = {
      id: vId,
      picUrl: this.data.picUrl,
      type: vType
    }
    console.log("入参===" + JSON.stringify(data));
    app.api.updateUserPicUrl(data).then(rest => {
      wx.hideLoading()
      if (rest && rest.success) {
        wx.showToast({
          title: '头像更新成功',
          icon: 'none',
          duration: 2000,
        })
      }
      this.upDataUserInfo(false)
    })
      .catch(r => {
        wx.hideLoading()
        console.error(r)
        wx.showToast({
          title: '头像更新失败，请稍后重试',
          icon: 'none',
          duration: 2000,
        })
      })
  },

  unBind: function () {
    this.hidePop()
    if (this.data.userInfo == null || this.data.userInfo.list == null || this.data.userInfo.list.length <= 0) {
      wx.showToast({
        title: '请先绑定小孩',
        icon: 'none',
        duration: 2000,
        mask: true
      })
      return
    }

    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '您确定要解除绑定吗？',
      success(res) {
        if (res.confirm) {
          that.unboundStudent();
        } else if (res.cancel) {
        }
      }
    })
  },

  exitApp: function () {
    this.hidePop()
    wx.showModal({
      title: '温馨提示',
      content: '确定退出登录吗？',
      success(res) {
        if (res.confirm) {
          app.loginOut()

          wx.redirectTo({
            url: '/pages/index/index',
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  addStudent: function () {
    this.hidePop()
    // var myThis = this;
    // wx.scanCode({
    //   success (res) {
    //     myThis.setData({
    //       showModal: true
    //     }),
    //     console.log(res)
    //   },
    //   fail(res){
    //     console.log("fail=="+res),
    //     myThis.setData({
    //       showModal: true
    //     })
    //   }
    // })
    wx.navigateTo({
      url: '/pages/addStu/addStu',
    })
  },

  hidePop() {
    if (this.data.userInfo != null && this.data.userInfo.list != null && this.data.userInfo.list.length > 0 && !this.data.ifTeacher) {
      // 关闭select  .对应class #对应id
      this.selectComponent("#select").close()
    }
  },

  //小孩选择弹框回调
  change(e) {
    var that = this
    var vIndex = e.detail.index
    var stuName = e.detail.name + "同学"
    var tHeadImge
    var vUserInfo = this.data.userInfo.list[vIndex]
    if(vUserInfo.img !=null){
      tHeadImge = vUserInfo.img
   }else{
      if(vUserInfo.sex == 1){
        tHeadImge = "/images/tx.png"
      }else{
        tHeadImge = "/images/txn.png"
      }
   }

    this.setData({
      //name:{...e.detail.name},
      name: stuName,
      stuIndex: vIndex,
      //stuInfo:that.data.userInfo.list[vIndex],
      className: that.data.userInfo.list[vIndex].schoolName + that.data.userInfo.list[vIndex].className,
      headImg: tHeadImge
    })
    this.updateStudentId()
  },


  upDataUserInfo(ifUpData) {
    console.log("入参===" + ifUpData);
    // 
    app.api.getUserInfo({}).then(rest => {
      if (rest && rest.success) {
        wx.setStorageSync('userData', rest.data)
        //上传头像、添加小孩时不用更新身份状态
        if (ifUpData) {
          if (rest.data.userType == 1 || rest.data.userType == 3) { //1老师 2家长 3 老师/家长
            wx.setStorageSync('ifTeacher', true)
          } else {
            wx.setStorageSync('ifTeacher', false)
          }
        }
        this.setData({
          ifTeacher: wx.getStorageSync('ifTeacher'),
          userInfo: wx.getStorageSync('userData'),
          stuIndex: wx.getStorageSync('stuIndex')
        })
        console.log('当前用户角色=======:' + this.data.ifTeacher + "   " + this.data.stuIndex)
        this.setUserData()
        console.log('setUserData')
      } else {
        console.log('添加小孩之后，获取数据失败')
      }
    })
      .catch(r => {
        console.error(r)


      })
  },

  //功能说明
  wxAppInfo() {
    this.hidePop()
    wx.navigateTo({
      "url": "/pages/outer/outer?webUrl=https://www.yuedone.com/h5/help.html"
      //==== "url": "/pages/outer/outer?webUrl=http://118.178.181.206/h5/help.html"

    })
  },

  //关于
  about() {
    this.hidePop()
    wx.navigateTo({
      url: '/pages/about/about',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    // 获取系统信息
    var ifTeacher = this.data.ifTeacher
    if (!ifTeacher) {
      var index = wx.getStorageSync('stuIndex');
      var tHeadImge
      if(this.data.userInfo.list[index].img !=null){
        tHeadImge = this.data.userInfo.list[index].img
     }else{
        if(this.data.userInfo.list[index].sex == 1){
          tHeadImge = "/images/tx.png"
        }else{
          tHeadImge = "/images/txn.png"
        }
     }


      this.setData({
        stuIndex: index,
        headImg: tHeadImge
      })
      console.log(this.data.stuIndex + "  headImg==" + this.data.headImg);
      this.selectComponent("#select").setViewData(this.data.stuIndex)
    }

  },

  onLoad: function (options) {

    if (options.addStu) {
      this.upDataUserInfo(false)
    } else {
      this.setData({
        ifTeacher: wx.getStorageSync('ifTeacher'),
        userInfo: wx.getStorageSync('userData'),
        stuIndex: wx.getStorageSync('stuIndex')
      })

      if (this.data.userInfo.list != null && this.data.userInfo.list.length > 0) {
        if (this.data.userInfo.list.length <= this.data.stuIndex) {
          this.setData({
            stuIndex: 0
          })
        }
      }

      console.log('当前用户角色=======:' + this.data.ifTeacher + "   " + this.data.stuIndex)
      this.setUserData()
    }
  },

  setUserData() {
    var ifTeacher = this.data.ifTeacher
    if (ifTeacher) {

      var headUrl = "/images/tx.png"
      if (this.data.userInfo.headUrl != null) {
        headUrl = this.data.userInfo.headUrl
      }
      this.setData({
        name: (this.data.userInfo.realName != null ? this.data.userInfo.realName + "老师" : "老师"),
        headImg: headUrl
      })
    } else {
      var tHeadImge
      var iFshowImg = true
      var vName = ''
      var vClassName = ''
      var vIfShowTeacherBut = false
      var vIfShowStuInfo = false
      if (this.data.userInfo.list != null && this.data.userInfo.list.length > 0) {
        console.log("位置11===" + this.data.stuIndex);
        if (this.data.userInfo.list[this.data.stuIndex].img != null) {
          console.log("位置22===" + this.data.stuIndex + "=====" + this.data.userInfo.list[this.data.stuIndex].img);
          tHeadImge = this.data.userInfo.list[this.data.stuIndex].img
        } else {
          if (this.data.userInfo.list[this.data.stuIndex].sex == 1) {
            tHeadImge = "/images/tx.png"
          } else {
            tHeadImge = "/images/txn.png"
          }
        }
        if (this.data.userInfo.list.length > 1) {
          iFshowImg = false //显示更多图标
        }
        // //没有学生信息时自动保存第一个
        // if(this.data.stuInfo == null){
        //   wx.setStorageSync('stuInfo', this.data.userInfo.list[0])
        //   wx.setStorageSync('stuIndex', 0)
        //   this.setData({
        //     stuInfo:this.data.userInfo.list[0],
        //     stuIndex:0
        //   })
        // }
        vName = this.data.userInfo.list[this.data.stuIndex].name + "同学",
          vClassName = this.data.userInfo.list[this.data.stuIndex].schoolName + this.data.userInfo.list[this.data.stuIndex].className
        vIfShowStuInfo = true
        console.log(vName + "=绑定小孩=" + vClassName);
      } else {
        console.log("未绑定小孩");
        tHeadImge = "/images/tx.png"
        vIfShowStuInfo = false
      }

      if (this.data.userInfo.userType == 1 || this.data.userInfo.userType == 3) {
        vIfShowTeacherBut = true
      } else {
        vIfShowTeacherBut = false
      }
      console.log("vIfShowTeacherBut===" + vIfShowTeacherBut);
      this.setData({
        name: vName,
        headImg: tHeadImge,
        className: vClassName,
        showImg: iFshowImg,
        ifShowTeacherBut: vIfShowTeacherBut,
        ifShowStuInfo: vIfShowStuInfo
      })

    }
  },


  //头像加载失败
  imgerr(e) {
    var ifTeacher = this.data.ifTeacher
    var tHeadImge
    if (ifTeacher) {
      tHeadImge = "/images/tx.png"
    } else {
      if (this.data.userInfo.list != null && this.data.userInfo.list.length > this.data.stuIndex) {
        if (this.data.userInfo.list[this.data.stuIndex].sex == 1) {
          tHeadImge = "/images/tx.png"
        } else {
          tHeadImge = "/images/txn.png"
        }
      } else {
        tHeadImge = "/images/tx.png"
      }
    }
    this.setData({
      headImg: tHeadImge
    })
  },

  //解除绑定
  unboundStudent() {
    wx.showLoading({
      title: '数据加载中...',
      icon: 'none',
    })
    //console.log(this.data.userInfo.appUserId+"====="+this.data.userInfo.list[this.data.stuIndex].studentId);
    var data = {
      id: this.data.userInfo.appUserId,
      studentId: this.data.userInfo.list[this.data.stuIndex].studentId,
    }
    app.api.unboundStudent(data).then(rest => {
      wx.hideLoading()
      if (rest && rest.success) {
        wx.showToast({
          title: '解绑成功',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        this.data.userInfo.list.splice(this.data.stuIndex, 1)

        if (this.data.userInfo.list != null && this.data.userInfo.list.length > 0) {
          this.selectComponent("#select").setViewData(0)
          this.setData({
            userInfo: this.data.userInfo,
            stuIndex: 0,
          })
        } else {
          this.setData({
            userInfo: {},
            stuIndex: 0,
            ifShowStuInfo: false
          })
        }
        wx.setStorageSync('stuIndex', 0)
        wx.setStorageSync('userData', this.data.userInfo)
        //console.log('接口数据bbbb='+JSON.stringify(this.data.userInfo))



        this.setUserData()

        //console.log('接口数据a='+JSON.stringify( wx.getStorageSync('stuInfo')))

      } else {

        console.log('接口数据==' + rest.errMsg)
        wx.showToast({
          title: rest.errMsg || '网络异常，请稍后重试！！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      }
    })
      .catch(r => {
        wx.hideLoading()
        console.error(r)
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      })
  },


  //切换身份
  updateUserType() {
    var that = this;
    wx.showLoading({
      title: '切换中...',
      icon: 'none',
    })
    var userType //1老师2家长
    if (this.data.ifTeacher) {
      userType = '2'
    } else {
      userType = '1'
    }
    console.log("切换用户角色身份==" + userType);
    wx.request({
      url: API_DOMAIN + 'app/appUser/updateUserType/', //仅为示例，并非真实的接口地址
      data: userType,
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': wx.getStorageSync('tokenId')
      },
      success(res) {
        that.setData({
          ifTeacher: !that.data.ifTeacher,
        })
        wx.setStorageSync('ifTeacher', that.data.ifTeacher)
        console.log('当前用户角色:' + wx.getStorageSync('ifTeacher'))
        that.setUserData()
        //console.log(res.data)
      }, complete() {
        wx.hideLoading()
      }
    })
  },


  //切换学生
  updateStudentId() {
    var that = this;
    wx.showLoading({
      title: '切换中...',
      icon: 'none',
    })
    wx.request({
      url: API_DOMAIN + 'app/appUser/updateStudentId/',
      data: this.data.userInfo.list[this.data.stuIndex].studentId,
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': wx.getStorageSync('tokenId')
      },
      success(res) {
        wx.setStorageSync('stuIndex', that.data.stuIndex)
        wx.showToast({
          title: '学生切换成功',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        console.log("切换学生===" + res.data)
      }, complete() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.hidePop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})